package cn.iocoder.yudao.module.scrm.service.marketing.content;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.category.MarketingCategoryRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.content.MarketingContentPageReqByTypeVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.content.MarketingContentPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.content.MarketingContentRespByTypeVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.content.MarketingContentSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.marketing.MarketingCategoryDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.marketing.MarketingContentDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.marketing.MarketingCategoryMapper;
import cn.iocoder.yudao.module.scrm.dal.mysql.marketing.MarketingContentMapper;
import cn.iocoder.yudao.module.scrm.service.marketing.category.MarketingCategoryService;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.MARKETING_CONTENT_NOT_EXISTS;

/**
 * 营销内容 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class MarketingContentServiceImpl implements MarketingContentService {

    @Resource
    private MarketingContentMapper marketingContentMapper;

    @Resource
    private MarketingCategoryMapper marketingCategoryMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private MarketingCategoryService marketingCategoryService;

    @Resource
    private PermissionApi permissionApi;

    @Override
    public Integer createMarketingContent(MarketingContentSaveReqVO createReqVO) {
        // 插入
        MarketingContentDO marketingContent = BeanUtils.toBean(createReqVO, MarketingContentDO.class);
        marketingContent.setCreator(Objects.requireNonNull(getLoginUserId()).toString());
        //将创建者的id改为用户姓名
        Optional.ofNullable(marketingContent.getCreator())
                .map(Long::valueOf)
                .map(adminUserApi::getUserNotCheckDataPermission)
                .map(response -> response.getCheckedData().getNickname())
                .ifPresent(marketingContent::setCreatorName);
        marketingContentMapper.insert(marketingContent);
        // 返回
        return marketingContent.getId();
    }

    @Override
    public void updateMarketingContent(MarketingContentSaveReqVO updateReqVO) {
        // 校验存在
        validateMarketingContentExists(updateReqVO.getId());
        // 更新
        MarketingContentDO updateObj = BeanUtils.toBean(updateReqVO, MarketingContentDO.class);
        marketingContentMapper.updateById(updateObj);
    }

    @Override
    public void deleteMarketingContent(Integer id) {
        // 校验存在
        validateMarketingContentExists(id);
        // 删除
        marketingContentMapper.deleteById(id);
    }

    private void validateMarketingContentExists(Integer id) {
        if (marketingContentMapper.selectById(id) == null) {
            throw exception(MARKETING_CONTENT_NOT_EXISTS);
        }
    }

    @Override
    public MarketingContentRespByTypeVO getMarketingContent(Integer id) {
        return marketingContentMapper.selectOne(id).getList().get(0);

    }

    @Override
    public PageResult<MarketingContentDO> getMarketingContentPage(MarketingContentPageReqVO pageReqVO) {
        return marketingContentMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<MarketingContentRespByTypeVO> getMarketingContentByTypePage(MarketingContentPageReqByTypeVO pageReqVO) {

        //查询父id下面所有子集
        if (pageReqVO.getCategoryId()!=null && !pageReqVO.getCategoryId().isEmpty()){
            List<String> allSubCategoryIds = marketingCategoryService.getAllSubCategoryIds(pageReqVO.getCategoryId());
            if (allSubCategoryIds!=null && !allSubCategoryIds.isEmpty()){
                pageReqVO.setCategoryIds(allSubCategoryIds);
            }
        }else{
            //根据营销类型查询当前类型的所有分类
            List<String> allSubCategoryIds = marketingCategoryService.selecAllIdsByType(pageReqVO.getMarketingType());
            if (allSubCategoryIds!=null && !allSubCategoryIds.isEmpty()){
                pageReqVO.setCategoryIds(allSubCategoryIds);
            }
        }

        if( !permissionApi.roleIsSuperAdmin(getLoginUserId()).getCheckedData()) {
            //超级管理员不进行设置
            //设置当前登陆人的部门id
            pageReqVO.setDeptId(String.valueOf(adminUserApi.getUser(getLoginUserId()).getCheckedData().getDeptId()));
        }


        //根据分类id及其子集查询内容
        PageResult<MarketingContentRespByTypeVO> marketingContentList = marketingContentMapper.selectByTypePage(pageReqVO);
        return marketingContentList;
    }

    @Override
    public PageResult<MarketingContentDO> notCheckDataPermissionTenant(MarketingContentPageReqVO pageReqVO) {
        return marketingContentMapper.notCheckDataPermissionTenant(pageReqVO);
    }

}